<template>
  <div class="return-pay-fee-manage-container animated fadeInRight">
    <!-- 查询条件 -->
    <el-card class="box-card">
      <div slot="header" class="flex justify-between">
        <span>{{ $t('returnPayFeeManage.search.title') }}</span>
        <el-button type="text" style="float: right; padding: 3px 0" @click="_moreCondition()">
          {{ returnPayFeeManageInfo.moreCondition ? $t('common.hide') : $t('common.more') }}
        </el-button>
      </div>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input v-model="returnPayFeeManageInfo.conditions.detailId"
            :placeholder="$t('returnPayFeeManage.search.detailId')" clearable />
        </el-col>
        <el-col :span="6">
          <el-select v-model="returnPayFeeManageInfo.conditions.feeTypeCd"
            :placeholder="$t('returnPayFeeManage.search.feeType')" style="width:100%" clearable>
            <el-option v-for="(item, index) in returnPayFeeManageInfo.feeTypes" :key="index" :label="item.name"
              :value="item.statusCd" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-select v-model="returnPayFeeManageInfo.conditions.state"
            :placeholder="$t('returnPayFeeManage.search.state')" style="width:100%" clearable>
            <el-option v-for="(item, index) in returnPayFeeManageInfo.returnPayFeeStates" :key="index" :label="item.name"
              :value="item.statusCd" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="_queryReturnPayFeeMethod()">
            <i class="el-icon-search"></i>
            {{ $t('common.search') }}
          </el-button>
          <el-button @click="_resetReturnPayFeeMethod()">
            <i class="el-icon-refresh"></i>
            {{ $t('common.reset') }}
          </el-button>
        </el-col>
      </el-row>

      <!-- 更多查询条件 -->
      <el-row v-show="returnPayFeeManageInfo.moreCondition" :gutter="20" style="margin-top:15px">
        <el-col :span="6">
          <el-input v-model="returnPayFeeManageInfo.conditions.applyPersonName"
            :placeholder="$t('returnPayFeeManage.search.applyPersonName')" clearable />
        </el-col>
        <el-col :span="6">
          <el-input v-model="returnPayFeeManageInfo.conditions.auditPersonName"
            :placeholder="$t('returnPayFeeManage.search.auditPersonName')" clearable />
        </el-col>
        <el-col :span="6">
          <el-input v-model="returnPayFeeManageInfo.conditions.payerObjName"
            :placeholder="$t('returnPayFeeManage.search.payerObjName')" clearable />
        </el-col>
      </el-row>

      <el-row v-show="returnPayFeeManageInfo.moreCondition" :gutter="20" style="margin-top:15px">
        <el-col :span="6">
          <el-date-picker v-model="returnPayFeeManageInfo.conditions.startTime" type="datetime"
            :placeholder="$t('returnPayFeeManage.search.startTime')" style="width:100%" />
        </el-col>
        <el-col :span="6">
          <el-date-picker v-model="returnPayFeeManageInfo.conditions.endTime" type="datetime"
            :placeholder="$t('returnPayFeeManage.search.endTime')" style="width:100%" />
        </el-col>
      </el-row>
    </el-card>

    <!-- 退费申请单列表 -->
    <el-card class="box-card" style="margin-top:20px">
      <div slot="header" class="flex justify-between">
        <span>{{ $t('returnPayFeeManage.list.title') }}</span>
        <!-- <el-button type="primary" size="small" @click="_exportFee()">
          {{ $t('common.export') }}
        </el-button> -->
      </div>

      <el-table :data="returnPayFeeManageInfo.returnPayFees" border style="width: 100%">
        <el-table-column prop="returnFeeId" :label="$t('returnPayFeeManage.table.returnFeeId')" align="center" />
        <el-table-column prop="detailId" :label="$t('returnPayFeeManage.table.detailId')" align="center" />
        <el-table-column prop="feeTypeCdName" :label="$t('returnPayFeeManage.table.feeType')" align="center" />
        <el-table-column prop="payerObjName" :label="$t('returnPayFeeManage.table.payerObjName')" align="center" />
        <el-table-column prop="cycles" :label="$t('returnPayFeeManage.table.cycles')" align="center" />
        <el-table-column :label="$t('returnPayFeeManage.table.amount')" align="center">
          <template slot-scope="scope">
            {{ scope.row.receivableAmount }}/{{ scope.row.receivedAmount }}<br>
            <template v-for="(item, index) in scope.row.feeAccountDetailDtoList" >
              <div v-if="item.state != '1001'" :key="index">
                {{ item.stateName }}: {{ item.amount }}<br>
              </div>
            </template>
            <div v-for="(item, index) in scope.row.payFeeDetailDiscountDtoList" :key="index">
              {{ item.discountName }}: {{ Math.abs(item.discountPrice) }}<br>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" :label="$t('returnPayFeeManage.table.createTime')" align="center" />
        <el-table-column prop="reason" :label="$t('returnPayFeeManage.table.reason')" align="center" />
        <el-table-column prop="applyPersonName" :label="$t('returnPayFeeManage.table.applyPersonName')" align="center">
          <template slot-scope="scope">
            {{ scope.row.applyPersonName || '-' }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('returnPayFeeManage.table.state')" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.state === '1100' ? 'success' : scope.row.state === '1200' ? 'danger' : 'info'">
              {{ scope.row.stateName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="auditPersonName" :label="$t('returnPayFeeManage.table.auditPersonName')" align="center">
          <template slot-scope="scope">
            {{ scope.row.auditPersonName || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="retundRemark" :label="$t('returnPayFeeManage.table.retundRemark')" align="center">
          <template slot-scope="scope">
            {{ scope.row.retundRemark || '-' }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('common.operation')" align="center" width="200">
          <template slot-scope="scope">
            <el-button v-if="scope.row.state == '1000'" size="mini" @click="_openReturnPayFeeAuditModel(scope.row)">
              {{ $t('common.audit') }}
            </el-button>
            <el-button v-if="scope.row.refundState == 'FT'" size="mini" @click="_tryRefundMoney(scope.row)">
              {{ $t('returnPayFeeManage.button.retryRefund') }}
            </el-button>
            <el-button size="mini" @click="_toReturnFeeDetail(scope.row)">
              {{ $t('common.detail') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination :current-page.sync="page.current" :page-sizes="[10, 20, 30, 50]" :page-size="page.size"
        :total="page.total" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </el-card>

    <!-- 审核组件 -->
    <audit-component ref="auditComponent" @notifyAuditInfo="notifyAuditInfo" />
  </div>
</template>

<script>
import { getDict, getCommunityId } from '@/api/community/communityApi'
import { listReturnPayFees, updateReturnPayFee, tryRefundMoney } from '@/api/fee/returnPayFeeManageApi'
import AuditComponent from '@/components/fee/audit'

export default {
  name: 'ReturnPayFeeManageList',
  components: {
    AuditComponent
  },
  data() {
    return {
      returnPayFeeManageInfo: {
        returnPayFees: [],
        total: 0,
        records: 1,
        moreCondition: false,
        returnPayFeeStates: [],
        feeTypes: [],
        conditions: {
          communityId: '',
          feeId: '',
          detailId: '',
          userCode: '',
          state: '1000',
          feeTypeCd: '',
          payerObjName: '',
          startTime: '',
          endTime: '',
          auditPersonName: '',
          applyPersonName: ''
        }
      },
      page: {
        current: 1,
        size: 10,
        total: 0
      }
    }
  },
  created() {
    this.returnPayFeeManageInfo.conditions.communityId = getCommunityId()
    this._initReturnPayFeeManage()
  },
  methods: {
    async _initReturnPayFeeManage() {
      try {
        const [feeTypes, returnPayFeeStates] = await Promise.all([
          getDict('pay_fee_config', 'fee_type_cd'),
          getDict('return_pay_fee', 'state')
        ])
        this.returnPayFeeManageInfo.feeTypes = feeTypes
        this.returnPayFeeManageInfo.returnPayFeeStates = returnPayFeeStates
        this._listReturnPayFees(this.page.current, this.page.size)
      } catch (error) {
        console.error('初始化数据失败:', error)
      }
    },
    async _listReturnPayFees(page, size) {
      try {
        this.returnPayFeeManageInfo.conditions.page = page
        this.returnPayFeeManageInfo.conditions.row = size
        const { data, total } = await listReturnPayFees(this.returnPayFeeManageInfo.conditions)

        if (data && data.length > 0) {
          data.forEach(item => {
            if (item.feeAccountDetailDtoList && item.feeAccountDetailDtoList.length > 0) {
              item.feeAccountDetailDtoList.forEach(item2 => {
                if (item2.state !== '1001' && item2.state !== '1003') {
                  item.receivedAmount = (parseFloat(item.receivedAmount) - parseFloat(item2.amount)).toFixed(2)
                }
              })
            }
          })
        }

        this.returnPayFeeManageInfo.returnPayFees = data
        this.page.total = total
      } catch (error) {
        console.error('获取退费申请单列表失败:', error)
      }
    },
    _queryReturnPayFeeMethod() {
      this.page.current = 1
      this._listReturnPayFees(this.page.current, this.page.size)
    },
    _resetReturnPayFeeMethod() {
      this.returnPayFeeManageInfo.conditions = {
        ...this.returnPayFeeManageInfo.conditions,
        detailId: '',
        feeTypeCd: '',
        state: '',
        payerObjName: '',
        startTime: '',
        endTime: '',
        applyPersonName: '',
        auditPersonName: ''
      }
      this._listReturnPayFees(this.page.current, this.page.size)
    },
    _moreCondition() {
      this.returnPayFeeManageInfo.moreCondition = !this.returnPayFeeManageInfo.moreCondition
    },
    _exportFee() {
      // 导出逻辑
      console.log('导出功能')
    },
    _openReturnPayFeeAuditModel(payFee) {
      this.returnPayFeeManageInfo.returnPayFee = payFee
      this.$refs.auditComponent.open()
    },
    async _auditReturnPayFeeState(auditInfo) {
      try {
        const returnPayFee = {
          ...this.returnPayFeeManageInfo.returnPayFee,
          state: auditInfo.state,
          payableAmount: 0.0,
          remark: auditInfo.state === '1200' ? `拒绝:${auditInfo.remark}` : auditInfo.remark
        }

        await updateReturnPayFee(returnPayFee)
        this.$message.success(this.$t('common.auditSuccess'))
        this._listReturnPayFees(this.page.current, this.page.size)
      } catch (error) {
        console.error('审核失败:', error)
        this.$message.error(error.message || this.$t('common.auditFailed'))
      }
    },
    async _tryRefundMoney(rPayFee) {
      try {
        const returnPayFee = {
          detailId: rPayFee.detailId,
          communityId: getCommunityId()
        }

        await tryRefundMoney(returnPayFee)
        this.$message.success(this.$t('returnPayFeeManage.message.refundSubmitSuccess'))
        this._listReturnPayFees(this.page.current, this.page.size)
      } catch (error) {
        console.error('提交退款失败:', error)
        this.$message.error(error.message || this.$t('returnPayFeeManage.message.refundSubmitFailed'))
      }
    },
    _toReturnFeeDetail(payFee) {
      this.$router.push(`/views/fee/propertyFee?feeId=${payFee.feeId}`)
    },
    notifyAuditInfo(auditInfo) {
      this._auditReturnPayFeeState(auditInfo)
    },
    handleSizeChange(val) {
      this.page.size = val
      this._listReturnPayFees(this.page.current, this.page.size)
    },
    handleCurrentChange(val) {
      this.page.current = val
      this._listReturnPayFees(this.page.current, this.page.size)
    }
  }
}
</script>

<style lang="scss" scoped>
.return-pay-fee-manage-container {
  padding: 20px;

  .box-card {
    margin-bottom: 20px;

    .clearfix {

      &:before,
      &:after {
        display: table;
        content: "";
      }

      &:after {
        clear: both;
      }
    }
  }

  .el-table {
    margin-top: 15px;
  }

  .el-pagination {
    margin-top: 15px;
    text-align: right;
  }
}
</style>